package com.ky.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ky.common.config.RedisKeyConfig;
import com.ky.common.course.entity.Address;
import com.ky.common.param.AddressAdd;
import com.ky.common.vo.R;
import com.ky.course.mapper.AddressMapper;
import com.ky.course.service.AddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ky.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 地址 服务实现类
 * </p>
 *
 * @author zpa
 * @since 2024-06-18
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据id获取地址列表
     *
     * @param token
     * @return
     */
    @Override
    public List<Address> getAddressList(String token) {

        User user = (User) redisTemplate.opsForValue().get(RedisKeyConfig.LOGIN_TOKEN + token);
        // 获取用户的id
        if(user==null || user.getId()==null){
            return null;
        }
        Integer userId = user.getId();
        List<Address> addressList = addressMapper.getAddressList(userId);


        return addressList;
    }

    @Override
    public boolean addAddress(String token, AddressAdd addAddress) {
        // 从redis 中获取用户的信息
        User user = (User) redisTemplate.opsForValue().get(RedisKeyConfig.LOGIN_TOKEN + token);
        // 获取用户的id
        if(user==null || user.getId()==null){
            return false;
        }
        Integer userId = user.getId();

        if (addAddress == null) {
            return false;
        }

        String isDefault = "";
        // 如果是默认地址, 将该用户的所有is_default 字段设置为0
        if (addAddress.getIsDefault()) {
            isDefault = "1";
            int i = addressMapper.resetIsDefault(userId);
            if (i <= 0) {
                return false;
            }
        } else {
            isDefault = "0";
        }

        Address address = new Address();
        address.setUserId(userId)
                .setName(addAddress.getName())
                .setPhoneNumber(addAddress.getTel())
                .setProvince(addAddress.getProvince())
                .setCity(addAddress.getCity())
                .setDistrict(addAddress.getCounty())
                .setDetailAddress(addAddress.getAddressDetail())
                .setIsDefault(isDefault);

        return addressMapper.insert(address) > 0;

    }

    @Override
    public boolean updateAddress(String token, AddressAdd addressAdd) {
        // 从redis 中获取用户的信息
        User user = (User) redisTemplate.opsForValue().get(RedisKeyConfig.LOGIN_TOKEN + token);
        // 获取用户的id
        if(user==null || user.getId()==null){
            return false;
        }
        Integer userId = user.getId();

        if (addressAdd == null) {
            return false;
        }

        // 查询要更新的地址在数据库中是否存在,是否是该该用户的
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("address_id", addressAdd.getId())
                .eq("user_id", userId);
        List<Address> addressList = addressMapper.selectList(queryWrapper);
        if (addressList==null || addressList.isEmpty()){
            return false;
        }

        // 是否为默认地址

        String isDefault = "";
        // 如果是默认地址, 将该用户的所有is_default 字段设置为0
        if (addressAdd.getIsDefault()) {
            isDefault = "1";
            int i = addressMapper.resetIsDefault(userId);
            if (i <= 0) {
                return false;
            }
        } else {
            isDefault = "0";
        }

        //更新地址
        Address address = addressList.get(0);
        address.setName(addressAdd.getName())
                .setPhoneNumber(addressAdd.getTel())
                .setCity(addressAdd.getCity())
                .setDistrict(addressAdd.getCounty())
                .setDetailAddress(addressAdd.getAddressDetail())
                .setIsDefault(isDefault)
                .setProvince(addressAdd.getProvince());
        QueryWrapper<Address> updateWrapper = new QueryWrapper<>();
        updateWrapper.eq("address_id", addressAdd.getId());
        int update = addressMapper.update(address, updateWrapper);
        return update > 0;
    }

    @Override
    public boolean deleteAddress(String token, AddressAdd addressAdd) {
        // 从redis 中获取用户的信息
        User user = (User) redisTemplate.opsForValue().get(RedisKeyConfig.LOGIN_TOKEN + token);
        // 获取用户的id
        if(user==null || user.getId()==null){
            return false;
        }
        Integer userId = user.getId();

        if (addressAdd == null) {
            return false;
        }

        // 查询要更新的地址在数据库中是否存在,是否是该该用户的
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("address_id", addressAdd.getId())
                .eq("user_id", userId);
        List<Address> addressList = addressMapper.selectList(queryWrapper);
        if (addressList==null || addressList.isEmpty()){
            return false;
        }
        return addressMapper.deleteById(addressAdd.getId()) > 0;
    }

    /**
     * 由 地址id  获取地址信息
     * @param token
     * @param id
     * @return
     */
    @Override
    public Address getByAddressId(String token, String id) {
        int addressId = Integer.parseInt(id);
        User user = (User) redisTemplate.opsForValue().get(RedisKeyConfig.LOGIN_TOKEN + token);
        // 获取用户的id
        if(user==null || user.getId()==null){
            return null;
        }
        return addressMapper.selectOne(new QueryWrapper<Address>().eq("address_id", addressId));
    }

    /**
     * 获取默认地址
     * @param token
     * @return
     */
    @Override
    public R getDefaultAddress(String token) {

        User user = (User) redisTemplate.opsForValue().get(RedisKeyConfig.LOGIN_TOKEN + token);
        // 获取用户的id
        if(user==null || user.getId()==null){
            return R.fail("用户未登录");
        }
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId())
                .eq("is_default", "1");
        return R.ok(addressMapper.selectOne(queryWrapper));
    }

}
